package com.znf4.banklink.bankpay;
/*package com.znf4.platform.banklink.bankpay;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bigpay.banklink.enums.BankLinkNetWorkStatusEnum;
import com.bigpay.banklink.exception.BankLinkBizException;
import com.bigpay.banklink.facade.CnpPayFacade;
import com.bigpay.banklink.facade.CnpPayVerifyFacade;
import com.bigpay.banklink.facade.QuickPayCommonFacade;
import com.bigpay.banklink.facade.QuickPayFacade;
import com.bigpay.banklink.utils.huixiang.HuiXiangConfigUtils;
import com.bigpay.banklink.utils.huixiang.MypaysRsaDataEncryptUtil;
import com.bigpay.banklink.utils.huixiang.ShortcutApi;
import com.bigpay.banklink.vo.CnpPayPreParam;
import com.bigpay.banklink.vo.CnpPayPreResult;
import com.bigpay.banklink.vo.CnpPayQueryParam;
import com.bigpay.banklink.vo.CnpPayQueryResult;
import com.bigpay.banklink.vo.NotifyVerifyParam;
import com.bigpay.banklink.vo.NotifyVerifyResult;
import com.bigpay.banklink.vo.QuickPayApplyParam;
import com.bigpay.banklink.vo.QuickPayApplyResult;
import com.bigpay.banklink.vo.QuickPayCommonApplyParam;
import com.bigpay.banklink.vo.QuickPayCommonApplyResult;
import com.bigpay.banklink.vo.QuickPayPreParam;
import com.bigpay.banklink.vo.QuickPayPreResult;
import com.bigpay.banklink.vo.QuickPayQueryParam;
import com.bigpay.banklink.vo.QuickPayQueryResult;
import com.bigpay.notify.entity.DyLog;
import com.bigpay.notify.service.RpNotifyService;
import com.bigpay.trade.dao.RpTradePaymentRecordDao;
import com.bigpay.trade.entity.RpTradePaymentRecord;
import com.bigpay.trade.enums.TradeSettStatus;
import com.bigpay.trade.enums.TradeStatusEnum;
import com.bigpay.user.entity.RpPayWay;
import com.bigpay.user.entity.RpUserPayConfig;
import com.bigpay.user.service.RpPayWayService;

import net.sf.json.JSONObject;

*//**
 * 汇享 快捷支付 D0
 *//*
@Service("QUICK_PAY_HUIXIANG_D0")
public class HuiXiangQuickPayD0 implements QuickPayCommonFacade, CnpPayVerifyFacade, CnpPayFacade  , QuickPayFacade {
	
	private static final Logger LOG = LoggerFactory.getLogger(HuiXiangQuickPayD0.class);

			
	@Autowired
	private RpTradePaymentRecordDao  rpTradePaymentRecordDao ;
	
	@Autowired
	private RpPayWayService rpPayWayService;
	
	@Autowired
	private RpNotifyService rpNotifyService;

	*//**
	 * 回调处理
	 *//*
	@Override
	public NotifyVerifyResult cnpPayVerify(NotifyVerifyParam notifyVerifyParam) {

		LOG.info("-------------------------汇享  快捷异步回调Start-----------------------");
		NotifyVerifyResult verifyResult = new NotifyVerifyResult();
		verifyResult.setBankChannelCode(notifyVerifyParam.getBankChannelCode());
		verifyResult.setResponseStr("success");
		// 结果通知参数，易联异步通知采用GET提交
		Map<String, Object> paramMap = notifyVerifyParam.getParamMap();

		System.out.println("汇享传给我的参数 ：" + paramMap.toString());

		*//***
		 * 汇享传给我的参数 ：{
		 * 
		 *              bankChannelReturnMsg={"client_trans_id":"DEV2017092010001393","resp_code":"PAY_SUCCESS","resp_msg":"成功","sign":"Ye58IARc/vxr0wB0VlnsXQFDXBWjyQxKZP4KFOS+g7l9ovLKfrZrmp0n8FK71pNjZ22HSqhXl4d7gE8E2VMqFhYxYexq3ubiH2rwGNCW4XbJN1KtoBflV520k96ziBwmZSxSeP3YqYBclgvm/JWgwZ8opF/rRC2G6XEiVs3xD0s="}}
		 * 具体逻辑代码
		 * 
		 *//*
		
		String json = paramMap.get("bankChannelReturnMsg").toString() ;
//		Map mapObj = JSONObject.parseObject(json ,Map.class);  
		Map<String, String> mapObj = toMap(json) ;
		
		String client_trans_id = mapObj.get("client_trans_id").toString() ;
		
		RpTradePaymentRecord rpTradePaymentRecord = rpTradePaymentRecordDao.getByBankOrderNo(client_trans_id); // 根据我们上送的订单号来处理
		// TODO 2017-07-10 新增订单号不存在逻辑处理
		if (null == rpTradePaymentRecord) {
			throw new RuntimeException("易联快捷异步回调时-支付流水订单号不存在！");
		}
		
		String resp_code = mapObj.get("resp_code").toString() ;
		String sign = mapObj.get("sign").toString() ;
		
		StringBuffer buf  = new StringBuffer() ;
		buf.append("client_trans_id=").append(client_trans_id) ;
		buf.append("|resp_code=").append(resp_code) ;
		
		boolean flag = false;
		try {
			flag = MypaysRsaDataEncryptUtil.rsaDataEncryptPub.verify(buf.toString().getBytes("UTF-8"), sign);
		} catch (Exception e) {
			LOG.info("汇享验签异常 ："  +  e.getMessage() );
			throw new RuntimeException( e.getMessage());
		}
		
		if(!flag){
			LOG.info("汇享回调签名失败 ：" + buf.toString() );
			verifyResult.setIsVerify(false);
		}
		
		if ("PAY_SUCCESS".equals(resp_code)) {       // 支付成功  ;
			verifyResult.setTradeStatusEnum(TradeStatusEnum.FINISH);
			verifyResult.setIsSett(true);  //结算
			verifyResult.setSettStatus(TradeSettStatus.COMPLETE_SETT);  // 结算
		System.out.println("验签成功---------------");	
			
		} else if ("PAY_SUBMIT".equals(resp_code)) { // 未支付
			verifyResult.setTradeStatusEnum(TradeStatusEnum.CREATED);
		} else if ("PAY_FAILURE".equals(resp_code)) { // 失败
			verifyResult.setTradeStatusEnum(TradeStatusEnum.FAILED);
		}
		
		// 构造以字符串内容为值的BigDecimal类型的变量payAmount
//		BigDecimal payAmount = new BigDecimal(amount);
//		// 设置小数位数，第一个变量是小数位数，第二个变量是取舍方法(四舍五入)   
//		payAmount = payAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
//		LOG.info("回调金额转换后payAmount【" + payAmount + "】");
//		verifyResult.setPayAmount(payAmount);// 支付金额
		
		verifyResult.setBankOrderNo(rpTradePaymentRecord.getBankOrderNo());
//		verifyResult.setBankTrxNo("");
		verifyResult.setBankStatus(mapObj.get("resp_msg").toString() );
		verifyResult.setBankSuccessTime(new Date());
		verifyResult.setIsVerify(true);
		
		LOG.info("-------------------------汇享快捷异步回调End-----------------------");
		return verifyResult;
	}

	*//**
	 * 快捷轮询-查询接口
	 *//*
	@Override
	public QuickPayQueryResult query(QuickPayQueryParam quickPayQueryParam) {

		LOG.info("快捷轮询-交易查询接口请求参数:{}", quickPayQueryParam);
		LOG.info("-------------------------汇享快捷查询Start-----------------------");

		QuickPayQueryResult quickPayQueryResult = new QuickPayQueryResult();
		quickPayQueryResult.setBankChannelCode(quickPayQueryParam.getBankChannelCode());
		quickPayQueryResult.setBankOrderNo(quickPayQueryParam.getBankOrderNo());
		quickPayQueryResult.setTradeStatusEnum(TradeStatusEnum.UNKNOWN);
		quickPayQueryResult.setBankSuccessTime(new Date());
		quickPayQueryResult.setSettStatus(TradeSettStatus.NOT_COMPLETE_SETT);// 未结算状态

		// 设置参数
		String merchOrderId = quickPayQueryParam.getBankOrderNo(); // 获取商户订单号
		// 调用查询接口
		LOG.info("订单查询商户订单号【" + merchOrderId + "】");
		Map<String, String> map;
		try {
			// 接口参数请参考TransactionClient的参数说明
			map = ShortcutApi.PayQry(merchOrderId);
			
			if ("PAY_SUCCESS".equals(map.get("resultCode"))) {       // 支付成功  ;
				quickPayQueryResult.setTradeStatusEnum(TradeStatusEnum.SUCCESS);
				quickPayQueryResult.setIsSett(true);  // 已结算
				quickPayQueryResult.setSettStatus(TradeSettStatus.COMPLETE_SETT) ;  // 已结算
				
			} else if ("PAY_SUBMIT".equals(map.get("resultCode"))) { // 未支付
				quickPayQueryResult.setTradeStatusEnum(TradeStatusEnum.WAITING_PAYMENT);
			} else if ("PAY_FAILURE".equals(map.get("resultCode"))) { // 失败
				quickPayQueryResult.setTradeStatusEnum(TradeStatusEnum.FAILED);
			}
			quickPayQueryResult.setBankReturnMsg(map.get("resultDesc"));

		} catch (Exception e) {
			throw new BankLinkBizException(BankLinkBizException.CHANNEL_NETWORK_ERRO,
					"请求上游易联快捷支付通道异常" + e.getMessage());
		}

		LOG.info(" 支付状态【" + map.toString() + "】");

		LOG.info("-------------------------汇享快捷查询End-----------------------");
		return quickPayQueryResult;
	}

	*//**
	 * D0 获取银联支付页面接口
	 *//*
	@Override
	public QuickPayCommonApplyResult payApply(QuickPayCommonApplyParam quickPayCommonApplyParam) {

		LOG.info("-------------------------汇享D0快捷支付-获取银联支付页面Start-----------------------");
		DyLog log = new DyLog();
		String logId = ""+System.currentTimeMillis()+(long)(Math.random() * 10000000L) ;
		*//****日志处理*****//*
		log.setId(logId);
		log.setBank_order_no(quickPayCommonApplyParam.getBankOrderNo());
	    log.setType("快捷");
	    log.setName("汇享D0-支付页面获取");
	    log.setRequest_packet(quickPayCommonApplyParam.toString());
	    rpNotifyService.sendRequestUpLog(log);
	    LOG.info("汇享D0-获取易连支付页面");
	    
	    
		QuickPayCommonApplyResult quickPayCommonApplyResult = new QuickPayCommonApplyResult();
        // 金额校验
		BigDecimal amount = quickPayCommonApplyParam.getOrderAmount();
		if (amount.doubleValue() <= BigDecimal.ZERO.doubleValue()) { // 金额小于0,打款失败
			quickPayCommonApplyResult.setTradeStatusEnum(TradeStatusEnum.FAILED);
			quickPayCommonApplyResult.setBankLinkNetWorkStatusEnum(BankLinkNetWorkStatusEnum.FAILED);
			return quickPayCommonApplyResult;
		}
		
		
		// 金额保留2位小数
		amount.setScale(2, RoundingMode.HALF_UP);
		DecimalFormat df = new DecimalFormat("###.00");
		String payAmount = df.format(amount).equals(".00") ? "0.00" : df.format(amount);
		if (payAmount.startsWith(".")) {
			payAmount = "0" + payAmount;
		}

		*//**
		 *  入参 
		 *//*
		boolean rateT0 = getRateT0(quickPayCommonApplyParam.getRpUserPayConfig() , quickPayCommonApplyParam.getObjectMap() ) ;
		if(!rateT0){
			LOG.error("汇享交易费率设置异常 {}+订单编号{} ：" , quickPayCommonApplyParam.getRpUserPayConfig().getUserNo() , quickPayCommonApplyParam.getObjectMap().get("bankOrderNo") );
			quickPayCommonApplyResult.setTradeStatusEnum(TradeStatusEnum.FAILED);
			quickPayCommonApplyResult.setBankLinkNetWorkStatusEnum(BankLinkNetWorkStatusEnum.FAILED);
		}
		
		quickPayCommonApplyParam.getObjectMap().put("rateT0", quickPayCommonApplyParam.getQuickPayCommonApplyVo().getMerchantPayRate().toString() ) ;
		quickPayCommonApplyParam.getObjectMap().put("notifyUrl", HuiXiangConfigUtils.getProperty("MERCHANT_NOTIFY_URL") + quickPayCommonApplyParam.getBankChannelCode() ) ;
		quickPayCommonApplyParam.getObjectMap().put("bankOrderNo", quickPayCommonApplyParam.getBankOrderNo() ) ;
		quickPayCommonApplyParam.getObjectMap().put("orderAmount", amountTransform(amount)  ) ;
		
		//到账金额
		BigDecimal pay_amount = BigDecimal.valueOf(Double.valueOf(quickPayCommonApplyParam.getObjectMap().get("payAmount"))) ;
		quickPayCommonApplyParam.getObjectMap().put("payAmount", amountTransform(pay_amount)  ) ;
		
		//手续费   单位分，向上取整，手续费=费率*交易金额
		BigDecimal operation_fee = BigDecimal.valueOf(Double.valueOf(quickPayCommonApplyParam.getObjectMap().get("operationFee"))) ;
		quickPayCommonApplyParam.getObjectMap().put("operationFee", amountTransform(operation_fee)  ) ;
				
		//单笔消费交易手续费  单位分，每笔固定交易手续费，比如200（2元）   : 和报备保持一致
		BigDecimal counter_fee_t0 = quickPayCommonApplyParam.getRpUserPayConfig().getCounterFee() ;
		quickPayCommonApplyParam.getObjectMap().put("counterFeeT0", amountTransform(counter_fee_t0)  ) ;
		
		Map<String, String> resultMap = null;
		try {
			// 接口参数请参考TransactionClient的参数说明
			resultMap = ShortcutApi.Pay(quickPayCommonApplyParam.getObjectMap());
			
			quickPayCommonApplyResult.setBankReturnMsg(resultMap.get("resultDesc"));  // 响应报文
			LOG.info("汇享支付结果响应状态码 :" + resultMap.get("resultCode"));
			if ("000000".equals(resultMap.get("resultCode"))) { // 发送短信成功-订单-等待支付

				LOG.info("发送验证码请求成功！");
				quickPayCommonApplyResult.setTradeStatusEnum(TradeStatusEnum.WAITING_PAYMENT); // 订单已创建
				quickPayCommonApplyResult.setBankLinkNetWorkStatusEnum(BankLinkNetWorkStatusEnum.PAYING); // 等待支付确认

				quickPayCommonApplyResult.setBankSuccessTime(new Date()); // 交易提交时间
				quickPayCommonApplyResult.setSettStatus(TradeSettStatus.NOT_COMPLETE_SETT);// 未结算状态


			} else { // 失败-直接订单失败
				LOG.info("汇享支付结果响应状态码描述  :" + resultMap.get("resultDesc"));
				quickPayCommonApplyResult.setTradeStatusEnum(TradeStatusEnum.FAILED);
				quickPayCommonApplyResult.setBankLinkNetWorkStatusEnum(BankLinkNetWorkStatusEnum.FAILED);
			}
		} catch (Exception e) {
			LOG.error("汇享交易发送失败异常：" + e.toString());
			quickPayCommonApplyResult.setTradeStatusEnum(TradeStatusEnum.FAILED);
			quickPayCommonApplyResult.setBankLinkNetWorkStatusEnum(BankLinkNetWorkStatusEnum.FAILED);
		}
		
		log.setResponse_packet(resultMap.toString());
	    rpNotifyService.sendResponseUpLog(log);
        LOG.info("汇享D0-获取银联支付页面响应报文发送到Mq");
		LOG.info("-------------------------汇享D0快捷支付-获取银联支付页面-End-----------------------");

		return quickPayCommonApplyResult;

	}

	*//**
	 * 大元的查询
	 *//*
	public CnpPayQueryResult cnpPayQuery(CnpPayQueryParam cnpPayQueryParam) {

		LOG.info("快捷平台-交易查询接口请求参数:{}", cnpPayQueryParam);
		LOG.info("-------------------------汇享快捷查询Start-----------------------");

		// 构造返回结果的数据结构
		CnpPayQueryResult cnpPayQueryResult = new CnpPayQueryResult();
		cnpPayQueryResult.setBankChannelCode(cnpPayQueryParam.getBankChannelCode());
		cnpPayQueryResult.setBankOrderNo(cnpPayQueryParam.getBankOrderNo());
		cnpPayQueryResult.setTradeStatusEnum(TradeStatusEnum.UNKNOWN);
		cnpPayQueryResult.setBankSuccessTime(new Date());
		// quickPayQueryResult.setSettStatus(TradeSettStatus.NOT_COMPLETE_SETT);//
		// 未结算状态 这个没找到对应字段

		// 设置参数
		String merchOrderId = cnpPayQueryParam.getBankOrderNo(); // 获取商户订单号

		// 调用查询接口
		LOG.info("订单查询商户订单号【" + merchOrderId + "】");
		Map<String, String> map;
		try {
			// 接口参数请参考TransactionClient的参数说明
			map = ShortcutApi.PayQry(merchOrderId);
			if ("PAY_SUCCESS".equals(map.get("resultCode"))) { // 已支付 ;
				cnpPayQueryResult.setTradeStatusEnum(TradeStatusEnum.SUCCESS);
				
			} else if ("PAY_SUBMIT".equals(map.get("resultCode"))) { // 支付中
				cnpPayQueryResult.setTradeStatusEnum(TradeStatusEnum.WAITING_PAYMENT);

			} else if ("PAY_FAILURE".equals(map.get("resultCode"))) { // 失败
				cnpPayQueryResult.setTradeStatusEnum(TradeStatusEnum.FAILED);
			}

		} catch (Exception e) {
			throw new BankLinkBizException(BankLinkBizException.CHANNEL_NETWORK_ERRO,
					"请求上游易联快捷支付通道异常" + e.getMessage());
		}

		LOG.info(" 支付状态【" + map.toString() + "】");

		LOG.info("-------------------------易联快捷查询End-----------------------");
		return cnpPayQueryResult;

	}

	
	
	*//**
	 * 金额类型转换
	 * @param amount
	 * @return
	 *//*
	public static String amountTransform(BigDecimal amount ){
		
		// 金额保留2位小数
		amount.setScale(2, RoundingMode.HALF_UP);
		
		amount = amount.multiply(new BigDecimal(100)) ;
		
		DecimalFormat df = new DecimalFormat("###");
		String payAmount = df.format(amount).equals(".00") ? "0.00" : df.format(amount);
		if (payAmount.startsWith(".")) {
			payAmount = "0" + payAmount;
		}
	System.out.println("金额是 ： " + payAmount );	
		return payAmount ;
	}
	
	
	*//**
	 * 获取用户设置的费率
	 * @return
	 *//*
	public boolean getRateT0(RpUserPayConfig rpUserPayConfig , Map<String , String > map ){
		
		List<RpPayWay> ways = rpPayWayService.listByProductCode(rpUserPayConfig.getProductCode());
		boolean shezhi = false;
		for (RpPayWay payWay : ways) {

			// 快捷T0
			if (payWay.getPayTypeCode().equals("QUICKPAY_D0")) {

				// 费率格式处理，保留后两位
				String rrate = "";
				int index = String.valueOf(payWay.getPayRate()).lastIndexOf(".");// 寻找小数点的索引位置，若不是小数，则为-1
				if (index > -1) {
					int len = String.valueOf(payWay.getPayRate()).substring(index + 1).length();// 取得小数点后的数值，不包括小数点
					if (len == 2) {
						double value = payWay.getPayRate() / 100;
						BigDecimal b = new BigDecimal(value);
						double Svalue = b.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
						rrate = String.valueOf(Svalue);
					} else {
						rrate = String.valueOf(payWay.getPayRate());
					}
				} else {
					return shezhi  ;
				}
				map.put("rateT0", rrate);    // 报备接口 ： 新增
				shezhi = true;
				return shezhi ;
			}
		}
		return  shezhi  ;
	}
	
	*//**
	 * json  转 map 
	 * @param object
	 * @return
	 *//*
	public Map<String, String> toMap(Object object) {
	    Map<String, String> data = new HashMap<String, String>();
	    // 将json字符串转换成jsonObject
	    JSONObject jsonObject = JSONObject.fromObject(object);
	    Iterator ite = jsonObject.keys();
	    // 遍历jsonObject数据,添加到Map对象
	    while (ite.hasNext()) {
	        String key = ite.next().toString();
	        String value = jsonObject.get(key).toString();
	        data.put(key, value);
	    }
	    // 或者直接将 jsonObject赋值给Map
	    // data = jsonObject;
	    return data;
	}
	
	
	
	
	
	
	
	
	*//**
	 * 汇享用不到的方法
	 * 该方法是：扫码支付的--支付接口
	 * (non-Javadoc)
	 * @see 
	 *//*
	@Override
	public CnpPayPreResult cnpPay(CnpPayPreParam cnpPayPreParam) {
		return null;
	}

	*//**
	 * 汇享用不到的方法
	 * 该方法是：快捷支付的-- 支付确认接口
	 *//*
	@Override
	public QuickPayCommonApplyResult pay(QuickPayCommonApplyParam quickPayCommonApplyParam) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public QuickPayApplyResult payApply(QuickPayApplyParam quickPayApplyParam) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public QuickPayPreResult pay(QuickPayPreParam quickPayPreParam) {
		// TODO Auto-generated method stub
		return null;
	}







}
*/